import React, { useEffect, useState } from 'react';

import MySwitchText from './MySwitchText';

import './index.css'

function _handleClick(_value, _setValue, props) {
  const { disabled, loading, onClick, onChange, } = props;

  if (disabled || loading) {
    typeof props.onClick === 'function' && onClick(_value);
    return false;
  }

  const newVal = !_value;
  _setValue(newVal);
  typeof onClick === 'function' && onClick(newVal);
  typeof onChange === 'function' && onChange(newVal);
}

const MySwitch = React.forwardRef((props, ref) => {
  const {
    disabled=false,
    checkedText=null,
    unCheckedText=null,
    defaultChecked=false,
    style={},
    small=false,
    loading=false,
    checked=null,
    onClick=null,
    onChange=null,
    themeColor=null,
  } = props;

  const [_value, _setValue] = useState(defaultChecked);
  const [_mouseDown, _setMouseDown] = useState(false);

  useEffect(() => {});

  if (checked !== null && checked !== _value) {
    _setValue(checked);
  }

  // 根据条件添加类名
  const _classNames = [ '_myswitch' ];
  if (_value) {
    _classNames.push('_checked');
    if (themeColor) {
      style.backgroundColor = themeColor;
    }
  }
  if (small) {
    _classNames.push('_small');
  }
  if (_mouseDown && !disabled && !loading) {
    _classNames.push('_mousedown');
  }
  if (disabled) {
    _classNames.push('_disabled');
  }
  if (loading) {
    _classNames.push('_disabled');
    _classNames.push('_loading');
  }

  const _handleClickProps = { disabled, loading, onClick, onChange, }

  return (
    <button
      className={_classNames.join(' ')}
      ref={ref}
      style={{...style}}
      onClick={() => _handleClick(_value, _setValue, _handleClickProps)}
      onMouseDown={(e) => {_setMouseDown(true)}}
      onMouseUp={(e) => {_setMouseDown(false)}}
    >
      
      <MySwitchText {...{checkedText, unCheckedText, _value}} />

      <span
        className="_block"
      >
      </span>
    </button>
  )
})

class OtherDemo extends React.Component {
  render() {
    return (
      <div>my switch</div>
    )
  }
}

MySwitch.OtherDemo = OtherDemo;

export default MySwitch;